package com.apptravel.web.controller.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;


import com.apptravel.component.MediaType;
import com.apptravel.component.Upload;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;


@Controller
@RequestMapping("/upload")
public class UploadController {

	private static final String IMAGE = "/image";
	private static final String MUSIC = "/music";
    private static final String PDF = "/pdf";

    private static final String UPLOAD_CONF_PATH = "classpath:upload.properties";


	private static final String UPLOAD_HTTP_KEY = "upload.http";
	
	@Autowired
	private Upload upload;
	

	@RequestMapping(IMAGE)
	public String uploadImage(MultipartHttpServletRequest request,HttpServletResponse response){
        Properties pros = new Properties();
		try{
			File confFile = ResourceUtils.getFile(UPLOAD_CONF_PATH);
			InputStream is = new FileInputStream(confFile);
			pros.load(is);
		}catch(Exception e){
			e.printStackTrace();
		}
        String uploadHttp = pros.getProperty(UPLOAD_HTTP_KEY);
		List<String> paths = upload.upload(request, MediaType.IMAGE);
		try{
			String type = request.getParameter("type");
			
			if(type == null || type.equals("0")){//swf�
				String json = JSONArray.fromObject(paths).toString();
				response.getWriter().print(json);
			}else if(type != null && type.equals("1")){//
				StringBuilder sb = new StringBuilder();
				sb.append("{'err':'','msg':{");
				sb.append("'url':'");
				sb.append(uploadHttp+paths.get(0));
				sb.append("','localname':'','id':''");
				sb.append("}}");
				response.getWriter().print(sb.toString());
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(MUSIC)
	public String uploadMusic(MultipartHttpServletRequest request,HttpServletResponse response){
		List<String> paths = upload.upload(request, MediaType.MUSIC);
		try{
			String json = JSONArray.fromObject(paths).toString();
			response.getWriter().print(json);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

    @RequestMapping(PDF)
    public String uploadPdf(MultipartHttpServletRequest request,HttpServletResponse response){
        List<String> paths = upload.upload(request, MediaType.PDF);
		try{
			String json = JSONArray.fromObject(paths).toString();
			response.getWriter().print(json);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
    }
	
	
}
